import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/store/auth'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/dashboard'
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/login/LoginView.vue'),
      meta: { title: '登录', requiresAuth: false }
    },
    {
      path: '/',
      component: () => import('@/views/layout/LayoutView.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('@/views/dashboard/DashboardView.vue'),
          meta: { title: '仪表盘', icon: 'lucide:layout-dashboard' }
        },
        {
          path: 'books',
          name: 'Books',
          component: () => import('@/views/books/BooksView.vue'),
          meta: { title: '图书管理', icon: 'lucide:book' }
        },
        {
          path: 'users',
          name: 'Users',
          component: () => import('@/views/users/UsersView.vue'),
          meta: { title: '用户管理', icon: 'lucide:user', requiresRole: 'ADMIN' }
        },
        {
          path: 'borrow',
          name: 'Borrow',
          component: () => import('@/views/borrow/BorrowView.vue'),
          meta: { title: '借阅记录', icon: 'lucide:refresh-cw' }
        },
        {
          path: 'settings',
          name: 'Settings',
          component: () => import('@/views/settings/SettingsView.vue'),
          meta: { title: '设置中心', icon: 'lucide:settings' }
        }
      ]
    }
  ]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()

  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 图书管理系统`
  }

  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    // 如果存在token但user为null，说明可能是页面刷新，尝试恢复用户信息
    if (authStore.token && !authStore.user) {
      console.log('路由守卫: 发现token但无用户信息，尝试恢复认证状态...', { to: to.path })
      try {
        const isValid = await authStore.checkAuth()
        console.log('路由守卫: 认证状态恢复结果:', isValid)
        if (!isValid) {
          console.log('路由守卫: 认证失败，跳转到登录页')
          next('/login')
          return
        }
      } catch (error) {
        console.error('路由守卫: 认证状态恢复失败:', error)
        next('/login')
        return
      }
    }

    // 重新检查认证状态
    if (!authStore.isAuthenticated) {
      console.log('路由守卫: 未认证，跳转到登录页', { to: to.path, hasToken: !!authStore.token })
      next('/login')
      return
    }

    // 检查角色权限
    if (to.meta.requiresRole && authStore.user?.role !== to.meta.requiresRole) {
      console.log('路由守卫: 角色权限不足，重定向到主页', { required: to.meta.requiresRole, userRole: authStore.user?.role })
      next('/dashboard')
      return
    }

    console.log('路由守卫: 认证通过，允许访问', { to: to.path })
  } else {
    console.log('路由守卫: 页面无需认证', { to: to.path })
  }

  // 已登录用户访问登录页，重定向到主页
  if (to.path === '/login' && authStore.isAuthenticated) {
    console.log('路由守卫: 已登录用户访问登录页，重定向到主页')
    next('/dashboard')
    return
  }

  next()
})

export default router
